#include "task_core.h"

void os_evsend(unsigned short tid, unsigned long ev)
{
	ostcb_t *ptcb;

	if(tid >= OSTASK_NUM) return;

	ptcb = &(g_task_tcb[tid]);
	ptcb->ev_write |= ev;

	if(TASKSTAT_BLOCK == ptcb->stat)
	{
		if(0 != (ptcb->ev_write & ptcb->ev_wait))
		{
			ptcb->stat = TASKSTAT_RUN;
		}
	}
}

int os_evwait(unsigned long wait_ev, int bwait, unsigned long *pev)
{
	ostcb_t *ptcb = gp_task_cur;

	ptcb->ev_wait = 0;

	if(0 != (wait_ev & ptcb->ev_write))
	{
		*pev = wait_ev & ptcb->ev_write;
		ptcb->ev_write &= ~wait_ev;

		return 0;
	}

	if(!bwait) return 1;

	ptcb->ev_wait = wait_ev;
	ptcb->stat = TASKSTAT_BLOCK;

	OS_TASK_BLOCK();

	*pev = wait_ev & ptcb->ev_write;
	ptcb->ev_write &= ~wait_ev;

	return 0;
}

int os_evrewait(unsigned long wait_ev, unsigned long *pev)
{
	ostcb_t *ptcb = gp_task_cur;

	ptcb->ev_wait = 0;

	if(0 != (wait_ev & ptcb->ev_write))
	{
		*pev = wait_ev & ptcb->ev_write;
		ptcb->ev_write &= ~wait_ev;
	}	

	ptcb->ev_wait = wait_ev;
	ptcb->stat = TASKSTAT_BLOCK;

	OS_TASK_BLOCK();

	*pev = wait_ev & ptcb->ev_write;
	ptcb->ev_write &= ~wait_ev;

	return 0;
}

